package com.example.tms.controller;

import com.example.tms.bean.ReturnInfo;
import com.example.tms.bean.UserInfo;
import com.example.tms.bean.UserView;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.SavedRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登录退出
 */
@RestController
public class LogController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //登录
    @RequestMapping(value = "/loginUser",method = RequestMethod.POST)
    public ReturnInfo userLogin(@RequestBody UserInfo userInfo){
        UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(userInfo.getYhm(),userInfo.getMima());
        Subject subject = SecurityUtils.getSubject();
        String b;
        try {
            subject.login(usernamePasswordToken);
            SecurityUtils.getSubject().getSession().setTimeout(-1000);
            logger.info("用户登录成功！ 用户名："+userInfo.getYhm()+" 密码："+userInfo.getMima());
            b = "登录成功！";
        }catch (Exception e){
            b = "帐号密码错误！";
        }
        return ReturnInfo.info1(b);
    }

    //退出
    @RequestMapping(value = "/logoutUser",method = RequestMethod.POST)
    public void userLogout(){
        Subject subject = SecurityUtils.getSubject();
        UserView userView = (UserView)subject.getPrincipal();
        System.out.println(userView.toString());
        logger.info("用户退出成功！ 用户名:"+userView.getYhm());
        subject.logout();
    }

}
